/***********************************************************************
 * Module:  ConnectState.java
 * Author:  Nikola
 * Purpose: Defines the Class ConnectState
 ***********************************************************************/

package genedit.controller;

import genedit.model.Workspace;
import genedit.model.graph.ConnectionPoint;
import genedit.model.graph.GraphElement;
import genedit.model.graph.Link;
import genedit.view.graph.ElementPainter;
import genedit.view.graph.GraphDocumentView;
import genedit.view.graph.GraphWorkArea;
import genedit.view.graph.LinkPainter;

import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

/**
 * stanje u koje se ulazi ukoliko je odabran rad sa nekim od veza
 * 
 * @author Igic
 * 
 */
public class ConnectState extends State {
	/** @param e */
	private Link link=null;
	public Creator factory;

	public void mouseReleased(MouseEvent e) {

	}

	/** @param e */
	public void mousePressed(MouseEvent e) {
		Point position = e.getPoint();
		GraphDocumentView activeView = Workspace.getInstance().getActiveDocument();
		if (activeView == null)
			return;
		if (e.getButton() != MouseEvent.BUTTON1)
			return;
		context.pointToUserSpace(position);
		//if (link == null) {
			// kreiramo vezu sa konekcijonom tackom na zadatoj poziciji unutar
			// grafickog elementa (el)
			ElementPainter el = activeView.getElementAtPosition(position);
			if (el != null && !(el instanceof LinkPainter)) {
				GraphElement element = el.getElement();
				ConnectionPoint cp = new ConnectionPoint(position);
				link = (Link) factory.instantiate(position, null);
				link.setStart(cp);
				element.addConnectionPoints(cp);
				cp.setParent(element);
				cp.addStarting(link);

				AddCommand addCommand = new AddCommand(false);
				addCommand.getAddedElements().add(link);
				addCommand.setDocument(context.getView());
				context.getView().getModel().getInvoker().executeCommand(addCommand);
				// context.getView().getWorkArea().repaint();

				((GraphWorkArea) activeView.getWorkArea()).getController().setCurrentState(
						new ActiveConnecting((GraphWorkArea) Workspace.getInstance()
								.getActiveDocument().getWorkArea(), link));
			}
			link=null;
		//}
	}

	/** @param e */
	public void keyPressed(KeyEvent e) {
		// TODO: implement
	}

	public void mouseMoved(MouseEvent e) {
		
	}

	public ConnectState(GraphWorkArea context, Creator factory) {
		super(context);
		this.factory = factory;
	}

}